package cn.regexp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopConsignee;
import cn.regexp.mapper.ConsigneeMapper;
import cn.regexp.service.IConsigneeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConsigneeServiceImpl extends ServiceImpl<ConsigneeMapper, ShopConsignee> implements IConsigneeService {
    @Autowired
    private ConsigneeMapper consigneeMapper;
    @Override
    public boolean saveConsignee(ShopConsignee consignee) {
        try {
            if (ObjectUtil.isNotEmpty(consignee.getId())) {
                // 更新操作
                // 判断是否设置为默认
                if (consignee.getIsDefault()) {
                    // 判断该用户是否已经设置默认收货人
                    // 查询该用户的默认收货人
                    QueryWrapper<ShopConsignee> wrapper = new QueryWrapper<>();
                    wrapper.eq("user_id", consignee.getUserId())
                            .eq("is_del", ShopConsignee.DELETE_NO)
                            .eq("is_default", Boolean.TRUE);
                    ShopConsignee defaultConsignee = consigneeMapper.selectOne(wrapper);
                    // 存在默认收货人，则修改其默认状态
                    if (ObjectUtil.isNotNull(defaultConsignee)) {
                        defaultConsignee.setIsDefault(Boolean.FALSE);
                        consigneeMapper.updateById(defaultConsignee);
                    }
                }
                // 保存用户修改的收货人
                consigneeMapper.updateById(consignee);
            } else {
                // 保存操作
                consignee.setIsDel(ShopConsignee.DELETE_NO);
                consigneeMapper.insert(consignee);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
